package com.study.system.course.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.edu.common.entity.Course;
import com.study.system.course.config.RabbitMQConfig;
import com.study.system.course.service.CourseService;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * 事件监听器
 */
@CanalEventListener
public class CanalListener {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private CourseService courseService;

    /**
     * 监听 erp数据库的customer表
     */
    @ListenPoint(schema = "edu_course",table = "course")
    public void updateData(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        System.out.println("修改前");
        //打印改变之前的数据
        rowData.getBeforeColumnsList().forEach((c)-> System.out.print(c.getName()+":"+c.getValue()+"\t"));
        System.out.println("\n修改后");
        //打印改变之后的数据
        rowData.getAfterColumnsList().forEach((c)-> System.out.print(c.getName()+":"+c.getValue()+"\t"));
        //判断操作类型
        if("INSERT".equals(eventType.name()) || "UPDATE".equals(eventType.name())){
            //遍历修改后的列，获得id的值，查询课程相关数据，使用mq发送JSON数据
            rowData.getAfterColumnsList().forEach( column -> {
                if("id".equals(column.getName())){
                    Course course = courseService.getCourseById(Integer.valueOf(column.getValue()));
                    rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_COURSE,
                            RabbitMQConfig.KEY_UPDATE,
                            JSON.toJSONString(course));
                }
            });
        }else if("DELETE".equals(eventType.name())){
            //遍历删除前的列，获得id，将id发送给mq
            rowData.getBeforeColumnsList().forEach(column -> {
                if("id".equals(column.getName())){
                    rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_COURSE,
                            RabbitMQConfig.KEY_DELETE,
                            column.getValue());
                }
            });
        }
    }
}